﻿using System;
using System.Net.Sockets;
using System.Threading;

namespace SC
{
    public class SocketClient
    {
        /// <summary>
        /// 连接失败事件
        /// </summary>
        public Action<String> connectError;
        /// <summary>
        /// 连接成功事件
        /// </summary>
        public delegate void ClientConnected();
        public ClientConnected clientConnected;
        /// <summary>
        /// 接受数据
        /// </summary>
        /// <param name="socket"></param>
        public delegate void RecvEvent(Socket socket);
        public RecvEvent recvEvent;

        private bool forceAbort = false;
        public Socket socket;
        private Thread receiveThread;

        public void ConnectServer(string ip, int port)
        {
            if (socket == null)
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            if (!socket.Connected)
            {
                try
                {
                    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(ip);
                    System.Net.IPEndPoint ipEp = new System.Net.IPEndPoint(iPAddress, port);
                    socket.BeginConnect(ipEp, new AsyncCallback(Connect), socket);
                    //接收消息线程
                    receiveThread = new Thread(new ThreadStart(Receive));
                    receiveThread.IsBackground = true;
                    receiveThread.Start();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

        }

        void Connect(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);
            }
            catch (Exception ex)
            {
                if (connectError != null)
                {
                    connectError(ex.Message);
                }
            }
            if (socket.Connected)
            {
                if (clientConnected != null)
                {
                    clientConnected();
                }
            }
        }

        /// <summary>
        /// 循环接收服务器发送的消息
        /// </summary>
        private void Receive()
        {
            try
            {
                while (!socket.Connected && !forceAbort) //等待连接成功
                {
                    System.Threading.Thread.Sleep(1000);
                }

                while (socket.Connected && !forceAbort) //等待退出连接
                {
                    if (recvEvent != null)
                    {
                        recvEvent(socket);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        /// <summary>
        /// 发送消息给服务器
        /// </summary>
        public int Send(byte[] buffer)
        {
            int count = 0;
            if (socket != null && socket.Connected)
            {
                try
                {
                    count = socket.Send(buffer);
                }
                catch (Exception e)
                {
                    //Debug.Log("Send错误:" + e.Message);
                    //Common.Log.Info("发型消息出错:",e);
                    throw e;
                }
            }
            return count;
        }

        /// <summary>
        /// 发送字节流类型数据
        /// </summary>
        /// <returns></returns>
        public int SendStream(byte[] buffer)
        {
            int count = 0;
            if (socket != null && socket.Connected)
            {
                try
                {
                    count = socket.Send(buffer);
                }
                catch (Exception e)
                {
                    //Common.Log.Info("发型消息出错:",e);
                    throw e;
                }
            }
            return count;
        }



        public void Close()
        {
            forceAbort = true;

            if (socket != null)
            {
                //关闭socket
                socket.Close();
            }
            if (receiveThread != null)
            {
                //终止线程
                receiveThread.Abort();
            }
        }
    }
}
